package com.example.util;
import com.example.demo.entity.CrRepairOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class FileUpUtil {

    private Logger logger = LoggerFactory.getLogger(CrRepairOrder.class);

    private String [] Englets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T"};

    /**
     * 文件上传方法
     * @param
     * @return
     */
    public String multiUpload(MultipartFile file ,String filePath) {
        try{
                if (file.isEmpty()) {
                    return "上传文件失败";
                }
                String fileName = file.getOriginalFilename();
                File dest = new File(filePath + fileName);
                file.transferTo(dest);
            logger.info("成功上传文件");
        }catch(Exception ex){

            logger.error("文件上传失败");
        }
        return "上传成功";
    }
   /* public String multiUpload(List<MultipartFile> files ,String filePath,String carNum) {
        System.out.println(files.size());
        try{
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                if (file.isEmpty()) {
                    return "上传第" + (i++) + "个文件失败";
                }
                String fileName = file.getOriginalFilename();

                File dest = new File(filePath + fileName);
                file.transferTo(dest);
                logger.info("第" + (i + 1) + "个文件上传成功");
            }
            logger.info("成功上传文件");
        }catch(Exception ex){

            logger.error("文件上传失败");
        }
        return "上传成功";
    }*/

    /**
     * 文件上传方法 spring 封装的方法
     * @param request
     * @return
     */
    public String  springUpload(HttpServletRequest request) throws IllegalStateException, IOException
    {
        long  startTime=System.currentTimeMillis();
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext())
            {

                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path="E:/springUpload"+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                }

            }

        }
        long  endTime=System.currentTimeMillis();
        System.out.println("Spring方法的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return "/success";
    }
    /**
     * 文件上传方法 流方式上传
     * @param
     * @return
     */
    public String  fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {

        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        System.out.println("fileName："+file.getOriginalFilename());

        try {
            //获取输出流
            OutputStream os=new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename());
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            byte[] bts = new byte[1024];
            //一个一个字节的读取并写入
            while(is.read(bts)!=-1)
            {
                os.write(bts);
            }
            os.flush();
            os.close();
            is.close();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("采用流上传的方式的运行时间："+String.valueOf(endTime-startTime)+"ms");
        return "/success";
    }

}
